package com.github.leecho.ssc.captcha.authentication;

import com.github.leecho.ssc.captcha.exception.CaptchaIncorrectException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;

/**
 * @author LIQIU
 * created on 2020/11/13
 **/
public class CaptchaAuthenticationProvider implements AuthenticationProvider {

    private final Logger log = LoggerFactory.getLogger(this.getClass());

    @Override
    public Authentication authenticate(Authentication authentication) throws AuthenticationException {
        UsernamePasswordAuthenticationToken authenticationToken = (UsernamePasswordAuthenticationToken) authentication;
        CaptchaAuthenticationDetails details = (CaptchaAuthenticationDetails) authenticationToken.getDetails();
        if (!details.isCaptchaMatch()) {
            //验证码不匹配抛出异常，退出认证
            if (log.isDebugEnabled()) {
                log.debug("认证失败：验证码不匹配");
            }
            throw new CaptchaIncorrectException("验证码错误");
        }
        //替换details
        authenticationToken.setDetails(details.getWebAuthenticationDetails());
        //返回空交给下一个provider进行认证
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return UsernamePasswordAuthenticationToken.class.isAssignableFrom(aClass);
    }

}
